package com.demo.socketchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * @author MT
 * @date 2019-12-10 10:08
 */
public class SocketChannelServer {
    public static void main(String[] args) throws IOException {
        // 创建serversocketchannel 监听8081端口
        ServerSocketChannel socketServer = ServerSocketChannel.open();
        // 通过serverSocket绑定8081端口
        socketServer.socket().bind(new InetSocketAddress(8081));
        //设置为非阻塞
        socketServer.configureBlocking(false);
        Selector selector = Selector.open();
        //Channel注册到selector上，必需在非阻塞模式下
        socketServer.register(selector, SelectionKey.OP_ACCEPT);

        // 创建处理器
        Handler handler = new Handler(1024);

        while (true) {
            if (Util.select(selector)) {
                continue;
            }
            System.out.println("\n处理请求");

            // 网上用的迭代器，这里使用foreach跟迭代器是一样的
            for (SelectionKey key : selector.selectedKeys()) {
                // 如果key是有效的

                // 接收到链接请求超时
                if (key.isValid() && key.isAcceptable()) {
                    handler.handleAccept(key);
                }
                // 读数据
                if (key.isValid() && key.isReadable()) {
                    System.out.println("可读：isReadable");
                    handler.handleRead(key);
                }
                // 写数据
                if (key.isValid() && key.isWritable()) {
                    System.out.println("可写：isWritable");
                    handler.handleWrite(key);
                }
                // 关闭客户端
//                handler.handleClose(key);
                // 移除已读取的key
                selector.selectedKeys().remove(key);
            }
        }
    }
}
